package com.leyou.user.controller;

import com.leyou.common.exception.LyException;
import com.leyou.user.domain.User;
import com.leyou.user.domain.UserDTO;
import com.leyou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.stream.Collectors;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("/check/{data}/{type}")
    public ResponseEntity<Boolean> checkUsername(@PathVariable String data, @PathVariable Integer type){
        Boolean result = userService.checkUsername(data,type);
        return ResponseEntity.ok(result);
    }

    @PostMapping("/code")
    public ResponseEntity<Void> sendCode(@RequestParam String phone){
        userService.sendCode(phone);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

    /**
     *
     * @param user
     * @param result BindingResult 必须要在@Valid注解参数后面
     * @param code
     * @return
     */
    @PostMapping("/register")
    public ResponseEntity<Void> register(@Valid User user, BindingResult result, @RequestParam String code){
        //判断时候有异常
        if(result.hasErrors()){
            String errorStr = result.getFieldErrors().stream().map(FieldError::getDefaultMessage)
                    .collect(Collectors.joining("|"));
            //抛出自定义 异常
            throw new LyException(500,errorStr);
        }
        userService.register(user,code);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping("/query")
    public ResponseEntity<UserDTO> queryUser(@RequestParam String username
    , @RequestParam String password){
        UserDTO userDTO = userService.queryUser(username,password);
        return ResponseEntity.ok(userDTO);
    }
}
